<template>
  <div class="project-detail-container">
    <a-card class="header-container" :bordered="false">
      <div class="breadcrumb-box">
        <a-breadcrumb>
          <a-breadcrumb-item>
            <span>{{ '<' }}</span>标注模块
          </a-breadcrumb-item>
          <a-breadcrumb-item>{{ breadcrumb }}</a-breadcrumb-item>
        </a-breadcrumb>
      </div>
      <div class="title">{{ breadcrumb }}</div>
    </a-card>
    <a-card class="cotent-container" :bordered="false">
      <a-steps :current="ProjectStoreData.step">
        <a-step>任务基本信息</a-step>
        <a-step>添加数据</a-step>
        <a-step>标注人员</a-step>
        <a-step>完成</a-step>
      </a-steps>
      <a-divider class="divider-range" />
      <div class="step-content">
        <a-form
          class="step-form"
          ref="stepForm"
          :model="ProjectStoreData.form"
          :rules="rules"
        >
          <Suspense>
            <component
              :key="componentId"
              :is="componentId"
              :disabled="disabled"
              :id="id"
              :layout="layout"
              :form="getStepForm"
              :status="status"
              :type="type"
              :commonList="ProjectStoreData.commonList"
              :compList="ProjectStoreData.compList"
              :compTotal="ProjectStoreData.compTotal"
              :toolList="ProjectStoreData.toolList"
              :lesionList="ProjectStoreData.lesionList"
              :userTotal="ProjectStoreData.userTotal"
              :userList="ProjectStoreData.userList"
              :companyList="ProjectStoreData.companyList"
              :watchFormData="watchFormData"
              :getFormLeisonDataList="getFormLeisonDataList"
              :clearLesionList="clearLesionList"
              :getCompData="getCompData"
              :getCompDialog="getCompDialog"
              :sortAlertTableData="sortAlertTableData"
              :clearAlertTableData="clearAlertTableData"
              :setSelectCheckAll="setSelectCheckAll"
              :clearSelectCheckAll="clearSelectCheckAll"
              :delCompAlertData="delCompAlertData"
              :delLesionData="delLesionData"
              :changeBizType="changeBizType"
              :existedName="existedName"
              :getUserList="getUserList"
              :addAnnoUserList="addAnnoUserList"
              :clearAnnoUserList="clearAnnoUserList"
              :delAnnoUserList="delAnnoUserList"
              :getUserDataList="getUserDataList"
              @updateData="handleGetData"
            ></component>
          </Suspense>
        </a-form>
      </div>
    </a-card>
    <a-card
      class="btn-container"
      :bordered="false"
      v-if="ProjectStoreData.step < 4"
    >
      <a-button @click="handleCancel">取消并返回</a-button>
      <a-button v-show="false" type="primary" style="background-color: #446197"
        >预览标注端</a-button
      >
      <a-button
        type="primary"
        v-show="ProjectStoreData.step <= 4 && ProjectStoreData.step > 1"
        @click="handleStepClick()"
        :loading="ProjectStoreData.ready"
        >上一步</a-button
      >
      <a-button
        type="primary"
        v-show="type === 'update' || ProjectStoreData.step >= 3"
        :loading="ProjectStoreData.ready"
        @click="handleSave"
        >保存提交</a-button
      >
      <a-button
        type="primary"
        v-show="ProjectStoreData.step >= 1 && ProjectStoreData.step < 3"
        :loading="ProjectStoreData.ready"
        @click="handleClick(true)"
        >下一步</a-button
      >
    </a-card>
  </div>
  <!-- 取消返回弹窗 -->
  <Dialog
    class="cancel-alert"
    :visible="visibile"
    title="提示"
    :width="420"
    :isForm="false"
    @update:visible="handleDialog"
  >
    <template v-slot>
      <div class="body-title">
        <icon-exclamation-circle-fill />
        返回将不保存编辑内容
      </div>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
  import { reactive, ref, computed, watch, watchEffect, Suspense } from 'vue';
  import { type LocationQuery, useRoute, useRouter } from 'vue-router';
  import { useProjectDetailStore } from '@/store';
  import { Message } from '@arco-design/web-vue';
  import FirstStep from './components/firstStep';
  import SecondStep from './components/secondStep';
  import ThirdStep from './components/thirdStep';
  import LastStep from './components/lastStep.vue';
  import Dialog from '@/components/dialog/index.vue';
  import type { CallBackData } from '@/components/dialog/type';

  const route = useRoute();
  const router = useRouter();
  const ProjectStoreData = useProjectDetailStore();
  const { type, status, id, layout } =
    route.query as LocationQuery as unknown as {
      type: 'create' | 'update';
      status: number;
      id?: number;
      layout?: string;
    };
  //查看or编辑、新建模式
  const disabled = computed(() => +status === 1 && type === 'update');
  const {
    initData,
    existedName,
    watchFormData,
    getProjectDetail,
    handleStepClick,
    saveData,
    getFormLeisonDataList,
    clearLesionList,
    resetFields,
    getCompData,
    getCompDialog,
    sortAlertTableData,
    clearAlertTableData,
    setSelectCheckAll,
    clearSelectCheckAll,
    delCompAlertData,
    delLesionData,
    changeBizType,
    getUserList,
    getCompanyData,
    addAnnoUserList,
    clearAnnoUserList,
    delAnnoUserList,
    getUserDataList,
  } = ProjectStoreData;
  const breadcrumb = ref(type === 'update' ? '编辑标注任务' : '新建标注任务');
  const componentEnums = {
    1: FirstStep,
    2: SecondStep,
    3: ThirdStep,
    4: LastStep,
  };
  const getStepForm = computed(() => ProjectStoreData.getStepForm);
  const componentId = computed(() => componentEnums[ProjectStoreData.step]);
  const stepForm = ref();
  const visibile = ref(false);//弹框显示/隐藏
  const rules = {
    'basicSetting.name': [
      {
        required: true,
        message: '任务名称不可为空',
      },
    ],
    'basicSetting.department': [
      {
        required: true,
        message: '科室不可为空',
      },
    ],
    'basicSetting.label': [
      {
        required: true,
        message: '任务标签不可为空',
      },
    ],
    'basicSetting.target': [
      {
        required: true,
        message: '任务目标不可为空',
      },
    ],
    'basicSetting.uses': [
      {
        required: true,
        message: '任务用途不可为空',
      },
    ],
    'basicSetting.discardCode': [
      {
        required: true,
        message: '废片原因不可为空',
      },
    ],
    'annoSetting.imageLayout': [
      {
        required: true,
        message: '影像布局不可为空',
      },
    ],
    'annoSetting.lesionList': [
      {
        required: true,
        message: '标注类型不可为空',
      },
    ],
    'annoUserSetting.beginDate': [
      {
        required: true,
        message: '开始时间不可为空',
      },
    ],
    'annoUserSetting.endDate': [
      {
        required: true,
        message: '结束时间不可为空',
      },
    ],
    'annoUserSetting.pubMethod': [
      {
        required: true,
        message: '任务方式不可为空',
      },
    ],
    'annoUserSetting.assignMethod': [
      {
        required: true,
        message: '任务分配方式不可为空',
      },
    ],
    'annoUserSetting.crossNum': [
      {
        required: true,
        message: '交叉次数不可为空',
      },
      {
        match: /^([2-9]|[1-4]\d|50)$/,
        message: '请输入2~50的整数',
      },
    ],
  };
  const handleCancel = () => {
    visibile.value = true;
  };
  const handleDialog = (data: CallBackData) => {
    if (data.status === 'save') {
      resetFields();
    }
    visibile.value = data.flag;
    router.push({
      name: 'Project',
    });
  };
  const handleGetData = (val: boolean) => {
    if (val) {
      stepForm.value.setFields({
        'basicSetting.name': {
          status: 'error',
          message: '任务名称已存在',
        },
      });
    }
  };
  initData();
  //获取任务详情
  if (type === 'update') {
    id && getProjectDetail(+id);
  }else{
    ProjectStoreData.ready = false//重置按钮loading状态
  }
  console.log("接口请求完成")
  watch(()=> ProjectStoreData.step, (pre, old) => {
    if (ProjectStoreData.step === 3) {//第三步要的基础数据
      getUserList();
      getCompanyData();
    }
  });
  // 步骤点击
  const handleClick = async (flag = false) => {
    // handleStepClick(flag);
    if (flag) {
      const validate = await stepForm.value.validate();
      if (!validate) {
        const status = validateTool();
        if (!status) {
          handleStepClick(flag);
        }
      }
    }
  };
  // 保存按钮点击
  const handleSave = async () => {
    const validate = await stepForm.value.validate();
    if (!validate) {
      const status = validateTool();
      if (!status) {
        saveData(type === 'create', id && +id);
      }
    }
  };
  // 校验病灶表格工具
  const validateTool = () => {
    let status = false;
    for(const lesion of ProjectStoreData.form.annoSetting.lesionDataList) {
      if (lesion.toolValueList.length === 0) {
        Message.error({
          content:
            ProjectStoreData.lesionList.find(
              (t) => t.value === lesion.lesionValue
            )?.name + '标注工具不可为空',
          id: lesion.lesionValue,
          position: 'top',
        });
        status = true;
        break
      }
      if(!lesion.color){
        Message.error({
          content:
              ProjectStoreData.lesionList.find(
                  (t) => t.value === lesion.lesionValue
              )?.name + '标注颜色不可为空',
          id: lesion.lesionValue,
          position: 'top',
        });
        status = true;
        break
      }
    }
    return status;
  };
</script>

<style scoped lang="less">
  @import url('./detail.less');
</style>
